<template>
  <DeviceCard :title="title" :status="statusText" custom-class="led-card">
    <div class="led-control">
      <span :class="ledStateClass">{{ ledState === 'on' ? '●' : '○' }}</span>
      <el-button @click="toggleLed" type="primary" :loading="isLoading">
        {{ ledState === 'on' ? '关闭' : '打开' }} LED
      </el-button>
    </div>
  </DeviceCard>
</template>

<script>
import DeviceCard from './DeviceCard.vue';
import socket from '../socket';  // 引入封装的socket模块

export default {
  name: 'LedLight',
  components: {
    DeviceCard
  },
  props: {
    deviceId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      title: 'LED 灯控制',
      ledState: 'off', // 初始状态为关闭
      isLoading: false
    };
  },
  computed: {
    statusText() {
      return this.ledState === 'on' ? '运行中' : '已关闭';
    },
    ledStateClass() {
      return {
        'led-indicator': true,
        'led-on': this.ledState === 'on',
        'led-off': this.ledState === 'off'
      };
    }
  },
  created() {
    // 订阅LED状态更新
    this.unsubscribe = socket.subscribeToDeviceUpdates('led', (data) => {
      // 只处理当前设备的更新
      if (data.deviceId === this.deviceId) {
        this.ledState = data.state;
      }
    });

    // 注册设备
    socket.socket.emit('register-device', {
      id: this.deviceId,
      type: 'led'
    });
  },
  methods: {
    toggleLed() {
      this.isLoading = true;
      const newState = this.ledState === 'on' ? 'off' : 'on';

      // 使用封装的socket方法发送命令
      socket.controlLed(newState);

      // 模拟响应处理
      setTimeout(() => {
        this.isLoading = false;
        this.ledState = newState;
        this.$message.success(`LED 已${newState === 'on' ? '打开' : '关闭'}`);
      }, 500);
    }
  },
  beforeDestroy() {
    // 取消订阅
    if (this.unsubscribe) {
      this.unsubscribe();
    }
  }
};
</script>

<style scoped>
.led-control {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  padding: 20px;
}

.led-indicator {
  font-size: 48px;
  transition: color 0.3s ease;
}

.led-on {
  color: #409eff;
}

.led-off {
  color: #909399;
}

.led-card {
  /* 样式保持不变 */
}
</style>